const {
  fileUpload,
  appealSubmit
} = require('../../../../../../api/index');
const {
  getDict
} = require('../../../../../../utils/dict');

const {
  validate
} = require('../../../../../../utils/util');

// pages/active/AssistanceCenter/pages/form/index.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    appealType: [],
    fileList: [],
    formData: {
      createStudentId: wx.getStorageSync('studentid'), // 学子id
      appealType: '', //  诉求类型
      appealPhoto: '', //  诉求图片
      processState: '00', //  默认未处理
      appealContent: '' //  诉求内容
    },
    rules: {
      appealType: [{
        empty: true,
        msg: '需求类型不能为空'
      }],
      appealContent: [{
        empty: true,
        msg: '反馈内容不能为空'
      }],
    }
  },
  async onSubmit(event) {
    //  判断返回的错误集合是否是空的，如果空则说明验证通过了，否则将错误显示到页面上
    const error = validate(this.data.formData, this.data.rules);
    if (error) { //  如果报错就不允许进行数据的提交
      this.setData({
        errors: error
      });
      return;
    }

    const {
      errors = []
    } = await appealSubmit(this.data.formData);
    if (errors.length > 0) {
      return;
    }

    //  提交成功 跳转到 成功页面
    const url = '/packageA/pages/active/AssistanceCenter/index';
    wx.navigateTo({
      url: `/packageA/pages/success/index?type=demand&url=${ url }`
    });
  },
  onFormData(event) { //  选择修改的内容, 注意不能异步
    const {
      prop
    } = event.currentTarget.dataset;
    this.data.formData[prop] = event.detail;
  },
  async afterRead(event) {
    const {
      file
    } = event.detail;
    const res = await fileUpload(file);

    const {
      fileList = []
    } = this.data;
    fileList.push({
      ...file,
      url: res.data.url
    });
    this.setData({
      fileList
    });

    //  设置上传数据
    this.data.formData.appealPhoto = res.data.fid;
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    this.setData({
      appealType: getDict('APPEAL_TYPE')
    });
  },
})